﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Vit.Web.Mvc;
using Vit.Web.Services;

namespace Vit.Web.Data
{
    public class DataRule<TContext, TEntity> : EntityRuleBase<TContext, TEntity>
        where TContext : DataContext, new()
        where TEntity : class, new()
    {
        protected MetadataTypeAccessor metaAccessor;

        public DataRule(IValidationService validationService, MetadataTypeAccessor metaAccessor)
            : base(validationService)
        {
            this.metaAccessor = metaAccessor;
        }

        public override Func<TEntity, bool> GetEntityKeyPredict(TEntity obj)
        {
            var md = metaAccessor.GetMetadataDescriptor(typeof(TEntity));
            MetadataTypeBase<TEntity> metadata = md.MetadataInstance as MetadataTypeBase<TEntity>;
            return metadata.GetEntityKeyPredict(obj);
        }

        internal MetadataTypeAccessor MetadataTypeAccessor
        {
            get { return this.metaAccessor; }
        }

        public static DataRule<TContext, TEntity> Create()
        {
            IUnityContainer unity = VitApplication.Current.UnityContainer;
            var rule = new DataRule<TContext, TEntity>(
                unity.Resolve<IValidationService>(),
                unity.Resolve<MetadataTypeAccessor>());

            return rule;
        }
    }
}
